<template>
  <Container class="role-edit">
    <div class="container-header title title-center" slot="header">
      {{ title }}
      <Button size="large" class="fl btn-back" icon="ios-arrow-back" @click="jumpPrevPage">返回</Button>
    </div>
    <div class="bgs">
      <Form :label-width="100" class="form" :model="form" ref="form" :rules="rules">
        <FormItem label="政策名称" prop="name">
          <Input
            :maxlength="20"
            class="common-width"
            v-model.trim="form.name"
            placeholder="请输入2-20位字符的政策名称"
          />
        </FormItem>
        <FormItem label="生效时间" prop="date">
          <DatePicker
            v-model="form.date"
            type="daterange"
            placeholder="请选择生效时间"
            class="common-width"
          ></DatePicker>
        </FormItem>
        <FormItem label="添加品牌">
          <Select v-model="inputModel" @on-change="onChange" multiple class="common-width">
            <Option
              v-for="item in  list.brandList"
              :value="item.brandId"
              :key="item.brandId"
            >{{item.brandName}}</Option>
          </Select>
        </FormItem>
      </Form>
      <div class="table-content">
        <p class="describle" v-if="list.tableInfoList.length<=0">暂时没有添加品牌哦,可以在下面下拉框添中加品牌</p>
        <div v-else>
          <div class="all-content" v-for="(item, idx) in list.tableInfoList" :key="idx">
            <Table border :columns="item.columns" :data="item.data"></Table>
          </div>
        </div>
      </div>
    </div>
    <Loader :status="status" @refresh="getInfo"></Loader>
    <div class="container-footer bg-white" slot="footer">
      <div>
        <Button type="primary" class="mr" size="large" :disabled="isDisabled" @click="onSave">保存</Button>
        <Button type="primary" class="mr" size="large" @click="cancle">取消</Button>
      </div>
    </div>
  </Container>
</template>
<script>
import table from "@/table";
import data from "./edit/InvalidBrandListEditItem";
import SelectList from "@/components/SelectList";
import { formatDate, getOriginData, getTireArr } from "@/util";
export default {
  components: {
    SelectList,
  },
  data() {
    const validateName = (rule, value, callback) => {
      if (value.trim() === "") {
        callback(new Error("请输入政策名称"));
      } else {
        if (value.length < 2) {
          callback(new Error("政策名称在2-20个字之间"));
        }
        callback();
      }
    };
    const validateDate = (rule, value, callback) => {
      if (value[0] === "") {
        callback(new Error("请输入时间"));
      }
      callback();
    };
    return {
      id: this.$route.query.id || "",
      title: "",
      status: "pass",
      isDisabled: false,
      inputModel: [],
      form: {
        name: "",
        brandId: "",
        date: [],
      },
      rules: {
        name: [{ required: true, validator: validateName, trigger: "blur" }],
        date: [{ required: true, validator: validateDate, trigger: "blur" }],
      },
      options: {
        tableHeight: 300,
      },
      storeType: [],
      brandList: [],
      replaceBrandList: [],
      list: data,
      policyItems: {},
    };
  },
  mounted() {
    this.initTable();
    this.$refs.form.resetFields();
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      this.title = "编辑政策";
    } else {
      this.title = "新增政策";
      this.list.tableInfoList = [];
    }
    this.initData();
  },
  destroyed() {
    this.$bus.$off();
  },
  methods: {
    ...table,
    async initData() {
      await this.getStoreList();
      await this.getBrandList();
      await this.getInfo();
    },
    getBrandList() {
      this.$ajaxGet("/product/common/supplier_brand").then((data) => {
        this.list.brandList = data;
      });
    },
    getStoreList() {
      return this.$ajaxGet("storeType/findAll").then((data) => {
        this.storeType = data.map((item) => {
          let obj = { storeTypeId: item.id, storeTypeName: item.name };
          return obj;
        });
      });
    },

    getInfo() {
      if (!this.id) return;
      this.status = "loading";
      return this.$ajaxGet(
        `/setting/brand_replacement_policy/detail/${this.id}`
      )
        .then((data) => {
          const {
            policyName,
            beginDate,
            endDate,
            brandList,
            policyItems,
          } = data;
          this.form.name = policyName;
          this.form.date = [formatDate(beginDate), formatDate(endDate)];
          this.inputModel = brandList.map((item) => {
            return item.brandId;
          });
          this.policyItems = policyItems;
          this.status = "pass";
        })
        .catch(() => {
          this.status = "error";
        });
    },
    getTableData() {
      this.list.tableInfoList.forEach((item) => {
        item.columns.push(
          {
            title: `抵${item.brandName}有效进货`,
            key: "storeTypeName",
            align: 'left',
            render: (h, p) => {
              return h("p", p.row.storeTypeName);
            },
          },
          {
            title: "抵上限(条/月)",
            key: "replaceMaxQuantity",
            align: 'left',
            render: (h, p) => {
              return h("InputNumber", {
                props: {
                  min: 0,
                  max: 1000,
                  size: "small",
                  value: p.row.replaceMaxQuantity,
                },
                on: {
                  "on-change": (e) => {
                    p.row.replaceMaxQuantity = e;
                    this.$set(item.data[p.index], "replaceMaxQuantity", e);
                  },
                },
              });
            },
          },
          {
            title: "用什么品牌抵",
            key: "replaceBrandName",
            align: 'left',
            render: (h, p) => {
              return h(
                "Select",
                {
                  props: {
                    value: p.row.replaceBrandName,
                    transfer:true
                  },
                  on: {
                    input: (val) => {
                      p.row.replaceBrandName = val;
                    },
                    "on-change": (e) => {
                      let x = item.replaceBrandList.find(
                        (s) => s.replaceBrandName == e
                      );
                      p.row.replaceBrandName = e;
                      p.row.replaceBrandId = x.replaceBrandId;
                      this.$set(item.data[p.index], "replaceBrandName", e);
                      this.$set(
                        item.data[p.index],
                        "replaceBrandId",
                        x.replaceBrandId
                      );
                    },
                  },
                },
                item.replaceBrandList.map((item) => {
                  return h("Option", {
                    props: {
                      value: item.replaceBrandName,
                      label: item.replaceBrandName,
                      key: item.brandId,
                    },
                  });
                })
              );
              p.row.replaceBrandName;
            },
          }
        );
        if (this.id) {
          item.data = this.policyItems;
          item.data = item.data.filter((e) => e.brandId == item.brandId).map(e=>{
            return{
                storeTypeName: e.storeTypeName,
                storeTypeId: e.storeTypeId,
                replaceMaxQuantity: e.replaceMaxQuantity ,
                brandId: e.brandId,
                brandName: e.brandName,
                replaceBrandName: e.replaceBrandName,
                replaceBrandId: e.replaceBrandId,
            }
          })
          if(!item.data.length){
             item.data = item.storeType.map((e) => {
              let obj = {
                storeTypeName: e.storeTypeName,
                storeTypeId: e.storeTypeId,
                replaceMaxQuantity: item.replaceMaxQuantity || 0,
                brandId: item.brandId,
                brandName: item.brandName,
                replaceBrandName: null,
                replaceBrandId: null,
              };
              return obj;
            });
          }

        } else {
          if (item.data.length == 0) {
            item.data = [];

            item.data = item.storeType.map((e) => {
              let obj = {
                storeTypeName: e.storeTypeName,
                storeTypeId: e.storeTypeId,
                replaceMaxQuantity: item.replaceMaxQuantity || 0,
                brandId: item.brandId,
                brandName: item.brandName,
                replaceBrandName: null,
                replaceBrandId: null,
              };
              return obj;
            });
          }
        }
      return item;
      });
    },
    onChange(s) {
      let all = getOriginData(this.list.brandList).map((item) => {
        const { brandId, brandName, id } = item;
        item.data = [];
        item.replaceBrandList = [];
        item.columns = [];
        item.storeType = this.storeType;
        item.replaceBrandList = getOriginData(this.list.brandList).filter(
          (e) => {
            return item.brandId != e.brandId;
          }
        );
        item.replaceBrandList = getOriginData(item.replaceBrandList).map(
          (v) => {
            return {
              replaceBrandId: v.brandId,
              replaceBrandName: v.brandName,
            };
          }
        );
        return item;
      });
      this.list.tableInfoList = all.filter((e) => {
        let v = s.find((i) => i == e.brandId);
        if (!v) {
          e.data = [];
        }
        return v;
      });
      this.getTableData();
    },
    getParamList() {
      let x = this.list.tableInfoList.find((e) => {
        return e.data.find(
          (v) => v.replaceMaxQuantity > 0 && v.replaceBrandName == null
        );
      });
      if (!x) {
        let arr = [];
        this.list.tableInfoList.forEach((s) => {
          s.data.filter((v) => {
            arr.push(v);
          });
        });
        return arr;
      }
    },
    onSave() {
      if (this.isDisabled) return;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let arr = this.getParamList();
          if (!arr) {
            this.$Message.error("选了多少条，必须选择抵扣品牌");
            return;
          }
          this.isDisabled = true;
          let url = this.id
            ? "/setting/brand_replacement_policy/modify"
            : "/setting/brand_replacement_policy/save";
          let text = this.id ? "编辑" : "新增";
          let param = {
            policyName: this.form.name || "",
            id: this.id ? this.id : "",
            brandReplacementPolicyItems: arr,
          };
          if (this.form.date[0])
            param.beginDate = formatDate(this.form.date[0]) + " 00:00:00";
          if (this.form.date[1])
            param.endDate = formatDate(this.form.date[1]) + " 23:59:59";
          this.$jsonPost(url, param)
            .then((data) => {
              this.$Notice.success({
                title: `${text}成功`,
              });
              this.$router.push("/policy/invalidBrand/list");
            })
            .catch(() => {
              this.isDisabled = false;
            });
        }
      });
    },
    cancle() {
      this.$router.back();
    },
    jumpPrevPage() {
      this.$router.back();
    },
  },
};
</script>
